package com.seeyon.apps.kk.manager;

import java.rmi.RemoteException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.axis2.transport.http.HttpTransportProperties;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSON;
import com.locknlock.gw.ifgw001.IFGW001_CN_GW_SOServiceStub;
import com.locknlock.gw.ifgw001.IFGW001_CN_GW_SOServiceStub.IFGW001_CN_GW_REQ_DT;
import com.locknlock.gw.ifgw001.IFGW001_CN_GW_SOServiceStub.IFGW001_CN_GW_REQ_MT;
import com.locknlock.gw.ifgw001.IFGW001_CN_GW_SOServiceStub.IFGW001_CN_GW_RES_MT;
import com.locknlock.gw.ifgw001.IFGW001_CN_GW_SOServiceStub.ITEM_type0;
import com.locknlock.gw.ifgw001.IFGW001_CN_GW_SOServiceStub.RETURN_type0;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.util.json.JSONUtil;
import com.seeyon.kk.utils.ValueUtils;
import com.seeyon.v3x.services.form.FormFactory;
import com.seeyon.v3x.services.form.FormUtils;
import com.seeyon.v3x.services.form.bean.FormExport;

public class LockCheckworkSapManager extends BaseManager {
	private static final Log log = LogFactory.getLog(LockCheckworkSapManager.class);
	private FreemarkFlowManager freemarkFlowManager;

	public FreemarkFlowManager getFreemarkFlowManager() {
		return freemarkFlowManager;
	}

	public void setFreemarkFlowManager(FreemarkFlowManager freemarkFlowManager) {
		this.freemarkFlowManager = freemarkFlowManager;
	}

	public void addCheckwordForm(Long id) {
		String sql = this.freemarkFlowManager.fltTemplateIntoString("sql/ghr/kqd/FIND_ALL_KQD_DATA.ftl", null);
		List<Map<String, Object>> v2 = this.jdbcTemplate.queryForList(sql, id);
		for (Map<String, Object> map : v2) {
			try {
				this.AddCheckworkLog(map);
				Map<String, Object> resultMap = this.addCheckwordForm(map);
				this.UpdateLog(resultMap);
			} catch (RemoteException | ParseException e) {
				log.error("locknlock 考勤确认单：", e);
			}
		}
	}

	public Map<String, Object> addCheckwordForm(Map<String, Object> map) throws RemoteException, ParseException {
		log.info(JSONUtil.toJSONString(map));
		if (!map.isEmpty()) {
			IFGW001_CN_GW_SOServiceStub stu = new IFGW001_CN_GW_SOServiceStub();
			HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
			auth.setUsername("IFPO01");
			auth.setPassword("Passpo1$");
			stu._getServiceClient().getOptions().setProperty(HTTPConstants.AUTHENTICATE, auth);
			IFGW001_CN_GW_REQ_MT iFGW001_CN_GW_REQ_MT0 = new IFGW001_CN_GW_REQ_MT();
			IFGW001_CN_GW_REQ_DT param = new IFGW001_CN_GW_REQ_DT();
			ITEM_type0[] sapV2 = new ITEM_type0[1];
			int num = 0;
			ITEM_type0 ii = new ITEM_type0();
			ii.setSRC_TRX_ID(MapUtils.getString(map, "邮箱唯一编号"));// 邮箱ID
			ii.setEMPNO(MapUtils.getString(map, "G-HR职员编号"));// 员工编号
			ii.setSEQ(MapUtils.getString(map, "SEQ"));// SEQID
			ii.setATT_TYPE(MapUtils.getString(map, "考勤区分"));// 考勤类型 为2
			log.info("考勤，上班时间验证："+ StringUtils.isNotBlank(MapUtils.getString(map, "上班时间")));
			log.info("考勤，下班时间验证："+ StringUtils.isNotBlank(MapUtils.getString(map, "下班时间")));
			if (StringUtils.isNotBlank(MapUtils.getString(map, "上班时间"))) {
				ii.setBGN_TIME(MapUtils.getString(map, "上班时间"));// 考勤开始时间
				ii.setEND_TIME("");// 考勤结束时间
				ii.setPUNCH_DATE(MapUtils.getString(map, "考勤日期1"));// 考勤日期
			} else if (StringUtils.isNotBlank(MapUtils.getString(map, "下班时间"))) {
				ii.setBGN_TIME("");// 考勤开始时间
				ii.setEND_TIME(MapUtils.getString(map, "下班时间"));
				ii.setPUNCH_DATE(MapUtils.getString(map, "考勤日期2"));// 考勤日期
			}
			ii.setREMARKS(MapUtils.getString(map, "事由"));// 事由
			ii.setGHR_STATUS("N");
			sapV2[num] = ii;
			num++;

			log.info("考勤确认书：" + JSONUtil.toJSONString(sapV2));
			param.setITEM(sapV2);
			iFGW001_CN_GW_REQ_MT0.setIFGW001_CN_GW_REQ_MT(param);
			IFGW001_CN_GW_RES_MT ifgw001_CN_GW_SO = stu.IFGW001_CN_GW_SO(iFGW001_CN_GW_REQ_MT0);
			RETURN_type0[] as = ifgw001_CN_GW_SO.getIFGW001_CN_GW_RES_MT().getRETURN();
			map.put("XIAOXI", as[0].getMESSAGE());
			map.put("STATUS", as[0].getSTATUS());
			map.put("IF_DATE", as[0].getIF_DATE());
			log.info("考勤确认书,return：" + JSONUtil.toJSONString(as));
		}
		return map;
	}

	public Map<String, Object> AddCheckworkLog(Map<String, Object> vm) {
		vm.put("types", "考勤确认书");// 推送类型
		String selectYsj = this.freemarkFlowManager.fltTemplateIntoString("sql/ghr/log/lock_kqdyuanshuju.ftl", vm);
		vm.put("source", selectYsj);// 推送源数据
		vm.put("agin", ValueUtils.getConfig().getLong("kk.CXCS"));// 是否重新传输
		vm.put("finsh", ValueUtils.getConfig().getLong("kk.WCPC"));// 完成抛送
		long mostSignificantBits = UUID.randomUUID().getMostSignificantBits();
		vm.put("SUIJI", mostSignificantBits);
		// 生成新的日志记录
		String dataXml = this.freemarkFlowManager.fltTemplateIntoString("sql/ghr/log/Lock_log.ftl", vm); // memberDay可以直接给
		// 可以使用数据模板生成，这样底表事件依然有效
		FormFactory formFactory = (FormFactory) AppContext.getBean("formFactory");
		try {
			FormExport[] formExportData = FormUtils.xmlTransformFormExports(dataXml);
			for (FormExport formExport : formExportData) {
				formFactory.importBusinessFormData("locknlockadmin", "Lock_log", formExport, null);
			}
		} catch (Exception e) {
			log.error("考勤确认书,添加底表日志：", e);
		}
		return vm;
	}

	public void UpdateLog(Map<String, Object> map) {
		Thread newThread = new Thread(new Runnable() {
			@Override
			public void run() {
				log.info("考勤确认单，更新日志 start：" + JSONUtil.toJSONString(map));
				Map<String, Object> msp = new HashMap<>();
				msp.put("IFDATE", MapUtils.getString(map, "IF_DATE"));
				msp.put("STATUS", MapUtils.getString(map, "STATUS"));
				msp.put("MESSAGE", MapUtils.getString(map, "XIAOXI") == null ? " " : MapUtils.getString(map, "XIAOXI"));
				msp.put("SUI", MapUtils.getString(map, "SUIJI"));
				int updateCount = -1;
				if (MapUtils.getString(map, "STATUS") == null || MapUtils.getString(map, "STATUS").equals("")) {
					msp.put("WPS", ValueUtils.getConfig().getLong("kk.LockLogWPS"));
					String updatesql = freemarkFlowManager.fltTemplateIntoString("sql/ghr/log/updatelogpssql.ftl", msp);
					log.info("考勤确认单，更新日志 sql：" + updatesql);
					updateCount = jdbcTemplate.update(updatesql);
				} else {
					msp.put("YPS", ValueUtils.getConfig().getLong("kk.lockLogYPS"));
					String updatesql = freemarkFlowManager.fltTemplateIntoString("sql/ghr/log/updatelogsql.ftl", msp);
					log.info("考勤确认单，更新日志 sql：" + updatesql);
					updateCount = jdbcTemplate.update(updatesql);
				}
				log.info("考勤确认单,更新日志 end：" + JSONUtil.toJSONString(msp) + ";updateCount:" + updateCount);
			}
		});

		newThread.start();
	}
}